package the.broccoli.uc.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import the.broccoli.ac.constant.ResType;
import the.broccoli.ac.dto.ResCondition;
import the.broccoli.ac.entity.Res;
import the.broccoli.ac.service.IResService;
import the.broccoli.uc.dto.ActionDTO;
import the.broccoli.uc.service.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 角色与资源服务类
 */
@Service
public class UserResServiceImpl implements IUserResService {

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IRoleResService roleResService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IResService resService;

    @Resource
    private ITenantAppService tenantAppService;

    /**
     * 获取功能资源列表
     * @param tenantId  租户ID
     * @param userId    用户ID
     * @return
     */
    @Override
    public List<ActionDTO> getActions(Integer tenantId, String userId) {
        List<String> roleList = userRoleService.getRoleIdList(userId);
        List<Res> roleActionList = null;
        if (roleService.isAdmin(roleList)) {
            roleActionList = selectResList(tenantId, Arrays.asList(ResType.ACTION.getValue()) );
        } else {
            roleActionList = roleResService.getResList(roleList, ResType.ACTION);
        }

        List<ActionDTO> data = null;
        if (!CollectionUtils.isEmpty(roleActionList)) {
            data = new ArrayList<>();
            ActionDTO dto = null;

            for (Res res : roleActionList) {
                dto = new ActionDTO(res);
                data.add(dto);
            }
        }
        return data;
    }

    /**
     * 获取资源列表
     * @param tenantId      租户ID
     * @param resTypeList   资源类型列表
     * @return
     */
    private List<Res> selectResList(Integer tenantId, List<String> resTypeList) {
        ResCondition condition = new ResCondition();
        condition.setAppIdList(tenantAppService.getAppIdList(tenantId));
        condition.setResTypeList(resTypeList);
        return resService.listByCondition(condition);
    }
}
